# client.py
import socket
from cryptography.fernet import Fernet

# 使用新生成的合法密钥（通过Fernet.generate_key()生成）
KEY = b'2DArf8mfLdgsDgwdnBQ5Uzr9zIRSEVerCnVk8Mn9xTQ='

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("127.0.0.1",8848))
cipher = Fernet(KEY)  # 使用合法密钥初始化加密器

while True:
    message = input("输入消息：")
    encrypted_msg = cipher.encrypt(message.encode("utf-8"))  # 加密消息
    client_socket.send(encrypted_msg)

    if message == "exit":
        break

    encrypted_data = client_socket.recv(1024)
    try:
        decrypted_data = cipher.decrypt(encrypted_data).decode("utf-8")  # 解密回复
        print(f"服务器回复：{decrypted_data}")
    except:
        print("解密失败！连接已终止")
        break

client_socket.close()